<?php


namespace addons\zzyy\controller;


use addons\zzyy\library\Yunding;
use addons\zzyy\library\Ykxbon;
use app\admin\model\zzyy\ZzyyReserve;
use app\admin\model\zzyy\ZzyyRoom;
use app\admin\model\zzyy\ZzyySetting;
use fast\Random;
use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\MqttClient;
use think\Config;
use think\Db;

/**
 * 定时任务
 */
class Autotask extends \think\addons\Controller
{
    protected $noNeedLogin = ["*"];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();

        if (!$this->request->isCli()) {
            $this->error('只允许在终端进行操作!');
        }
    }

    /**
     * 定时任务逻辑
     */
    public function index()
    {
        // 更新订单是否超时
        $payCountdownSec = ZzyySetting::getPayCountdownSec();

        if ($payCountdownSec > 0) {   //有效设置
            $reserves = ZzyyReserve::where('starttime', '>', Ykxbon::now()->startOfDay()->toDateTimeString())
                ->where('status', ZzyyReserve::STATUS_CREATED)
                ->select();
            foreach ($reserves as $reserve) {
                if (time() >  $payCountdownSec + $reserve->createtime) {
                    $reserve->delete();
                }
            }
        }

        echo "done";
        return;
    }

    /**
     * 电源定时任务
     */
    public function elemetor()
    {
        @ini_set("memory_limit", '-1');
        $stime = microtime(true);

        $config = get_addon_config('zzyy');
        if (empty($config['tongtongsuo_domain'])
            || empty($config['tongtongsuo_client_id'])
            || empty($config['tongtongsuo_client_secret'])
            || empty($config['tongtongsuo_username'])
            || empty($config['tongtongsuo_password']) ) {
            echo '未配置云丁电源';
            exit;
        }

        //得到要处理的教室
        $rooms = ZzyyRoom::all();

        $yunding = new Yunding();

        foreach ($rooms as $room) {
            sleep(2);
            echo $room->room_name . PHP_EOL;
            //判断是否有配置homeid和uuid, 没有配置，不做操作
            if (empty($room->yunding_homeid) or empty($room->yunding_elemetor_uuid)) {
                continue;
            }
            //得到电表的当前状态
            $isOn = $yunding->isElemeterSwitchOn($room->yunding_homeid, $room->yunding_elemetor_uuid);
            echo 'current: ';
            echo $isOn ? 'on' : 'off';
            echo PHP_EOL;

            //当前时间是否有预约， 在预约中，不做任何操作
            $isRunning = ZzyyReserve::where('starttime', '<', Ykxbon::now()->toDateTimeString())
                ->where('endtime', '>', Ykxbon::now()->toDateTimeString())
                ->where('room_id', $room->id)
                ->where('status', ZzyyReserve::STATUS_SUCCESS)
                ->count();

            if ($isRunning) {
                echo 'is runing' . PHP_EOL;
                if ($isOn) {
                } else {
                    $yunding->elemeterSwitchOn($room->yunding_homeid, $room->yunding_elemetor_uuid);
                }
                continue;
            }

            //5,15,25,35,45,55
            //得到此教室未来12分钟内是否有预约， 有预约， 通电，没有预约，关电
            $wiilRunning = ZzyyReserve::where('starttime', '<', Ykxbon::now()->addMinute(12)->toDateTimeString())
                ->where('endtime', '>', Ykxbon::now()->addMinute(12)->toDateTimeString())
                ->where('room_id', $room->id)
                ->where('status', ZzyyReserve::STATUS_SUCCESS)
                ->count();

            if ($wiilRunning) { //开
                echo 'will runing: yes' . PHP_EOL;
                if ($isOn) {

                } else {
                    $yunding->elemeterSwitchOn($room->yunding_homeid, $room->yunding_elemetor_uuid);
                }

            } else { //关
                echo 'will runing: no' . PHP_EOL;
                if ($isOn) {
                    $yunding->elemeterSwitchOff($room->yunding_homeid, $room->yunding_elemetor_uuid);
                } else {

                }
            }
        }

        $etime = microtime(true);//获取程序执行结束的时间
        $total = $etime - $stime;   //计算差值
        echo $total;

    }

    /**
     * 音响定时任务
     */
    public function audioDevice()
    {
        @ini_set("memory_limit", '-1');
        $stime = microtime(true);

        $config = get_addon_config('zzyy');
        if (empty($config['mqtt_address'])
            || empty($config['mqtt_port'])
            || empty($config['mqtt_user'])
            || empty($config['mqtt_password'])) {
            echo '未配置mqtt';
            exit;
        }

        //当前时间是否有预约， 在预约中，不做任何操作
        $reserves = ZzyyReserve::with('room')
            ->where('endtime',  '>', Ykxbon::now()->startOfDay()->toDateTimeString())
            ->where('endtime', '<', Ykxbon::now()->endOfDay()->toDateTimeString())
            ->where('status', ZzyyReserve::STATUS_SUCCESS)
            ->select();

        foreach ($reserves as $v) {
            $IMIE = $v->room->audio_device;
            if (empty($IMIE)) {
                echo '未配置音响的IMIE';
                continue;
            }

            $clientId = '888888';
            $clean_session = false;
            $topic = $IMIE;
            $connectionSettings = new ConnectionSettings();
            $connectionSettings
                ->setUsername($config['mqtt_user'])
                ->setPassword($config['mqtt_password'])
                ->setKeepAliveInterval(60)
                ->setLastWillQualityOfService(1);

            $mqtt = new MqttClient($config['mqtt_address'], $config['mqtt_port'], $clientId);
            $mqtt->connect($connectionSettings, $clean_session);
            printf("client connected\n");

            echo 'endtime: ' . Ykxbon::parse($v->endtime)->getTimestamp();
            echo 'now: ' . Ykxbon::now()->getTimestamp();
            $diffSec = Ykxbon::parse($v->endtime)->getTimestamp() - Ykxbon::now()->getTimestamp();
            echo $diffSec . PHP_EOL;

            $msgId = Ykxbon::now()->format("YmdHis") . Random::alnum(10);
            $remindMin = 3;

            if ($diffSec <= 60 && $diffSec >= 0) { // 结束的语音播报
                $ZPL = "$IMIE|1007-2|$msgId|7573|-|7573";
                $mqtt->publish($topic, $ZPL, 0);
            }
            if ($diffSec <= 60 * $remindMin && $diffSec >= 60 * ($remindMin - 1)) { // 距离10分钟的播报
                $ZPL = "$IMIE|1007-2|$msgId|7571|$remindMin|7572";
                $mqtt->publish($topic, $ZPL, 0);
            }
        }

        $etime = microtime(true);//获取程序执行结束的时间
        $total = $etime - $stime;   //计算差值
        echo $total;

    }
}